package org.example.gradleDemo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@SuppressWarnings("ALL")
public  class TcpClientDemo {

    public static void main(String[] args) {
        System.out.println("tcp client start" );

        TcpClientDemo client = new TcpClientDemo();
        client.StartClient();

        System.out.println("tcp client end" );

    }



    public  void StartClient()
     {
         try
         {
             Charset utf8 = StandardCharsets.UTF_8;

             SocketChannel socketChannel = SocketChannel.open();
             socketChannel.configureBlocking(false);
             InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 9527);

             if(!socketChannel.connect(inetSocketAddress)) {
                 while (!socketChannel.finishConnect()) {
                     System.out.println("客户端正在连接中，请耐心等待");
                 }
             }


            // ByteBuffer byteBuffer = ByteBuffer.wrap("client hello".getBytes(utf8));
            // socketChannel.write(byteBuffer);
            // socketChannel.close();

           //  ByteBuffer writeBuffer = ByteBuffer.allocate(32);
             ByteBuffer readBuffer = ByteBuffer.allocate(32);

             utf8.encode("hello");

            // writeBuffer.put("hello".getBytes());
            // writeBuffer.flip();

             while (true) {

                 var writeBuffer =    utf8.encode("hello");
                // writeBuffer.flip();
                 System.out.println("send to server :" +writeBuffer.limit());
                 socketChannel.write(writeBuffer);
                 writeBuffer.rewind();

                 readBuffer.clear();
                 socketChannel.read(readBuffer);
               // readBuffer.flip();
                 var content = utf8.decode(readBuffer).toString();
                 System.out.println("server response :" +content);

                 Thread.sleep(3000);
             }
         }
         catch (IOException | InterruptedException io)
         {
             System.out.println(" client error:"+ io.getMessage());
         }



     }
}
